#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <unordered_map>
#include "TcpServe.h"
#include "HttpProtocol.h"
using http_handler_t = std::function<void(HttpRequest &, HttpResponse &)>;
using namespace TcpServeMoule;

const std::string balck = Sep;
class HttpServe
{
public:
    HttpServe(int port)
        : _tsvr(std::make_unique<TcpServe>(port))
    {
    }
    void Resgiter(std::string funcname, http_handler_t func)
    {
        _route[funcname] = func;
    }
    bool SafeCheck(const std::string &service)
    {
        auto iter = _route.find(service);
        return iter != _route.end();
    }
    void Start()
    {
        _tsvr->Init([this](SockPtr sockfd, IntAddr addr)
                    { return this->HandlerHttpRequest(sockfd, addr); });
        _tsvr->Loop();
    }
    bool HandlerHttpRequest(SockPtr sockfd, IntAddr addr)
    {
        LOG(LogLevel::DEBUG) << "HttpServer: get a new client: " << sockfd->Fd() << " addr info: " << addr.Addr();
        std::string http_request;
        sockfd->Recv(&http_request);
        HttpRequest req;
        req.Deserialize(http_request);
        HttpResponse resp;
        if (req.IsHasArgs())
        {
            std::cout << "-----IsHasArgs()" << std::endl;
            // 2. 提交参数，携带参数，需要我们进行交互设置
            std::string service = req.Path();
            if (SafeCheck(service))
                _route[req.Path()](req, resp); // /login
            else
                resp.Build(req); // debug
        }
        else
        {
            std::cout << "-----Non IsHasArgs()" << std::endl;
            resp.Build(req);
        }

        std::string resp_str;

        resp.SeriaLize(&resp_str);
        std::cout << resp_str << std::endl;
        sockfd->Send(resp_str);
        return true;
        // std::cout << http_request;
        // std::string status_line = "HTTp/1.1 200 OK" + Sep + balck;

        // std::string body = "<!DOCTYPE html>\
        //                     <html>\
        //                   <head>\
        //                    <meta charset = \"UTF-8\">\
        //                    <title> Hello World</title>\
        //                    </head>\
        //                    <body>\
        //                     <p> Hello World</ p>\
        //                   </body> </html>";

        // std::string httpreponse = status_line + body;
        // sockfd->Send(httpreponse);
        return true;
    }
    ~HttpServe()
    {
    }

private:
    std::unique_ptr<TcpServe> _tsvr;
    std::unordered_map<std::string, http_handler_t> _route;
};
